package top.pmwly.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import top.pmwly.hadler.MyAccessDeniedHandler;
import top.pmwly.hadler.MyAuthentiactionFailurHandler;
import top.pmwly.hadler.MyAuthenticationSuccessHandler;

/**
 * @author Herther
 * @version 1.0.0
 * @ClassName SecurityConfig.java
 * @Description
 * @createTime 2021年08月17日 17:41:00
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private MyAccessDeniedHandler myAccessDeniedHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //表单登录
        http.formLogin()
                //自定义的登录页面
                .loginPage("/login.html")
                //自定义的登录逻辑
                .loginProcessingUrl("/login")
                //登录成功后跳转的 页面， 必须是post请求
                .successForwardUrl("/toMain")
                //.successHandler(new MyAuthenticationSuccessHandler("/main.html"))
                //失败后跳转页面，必须是post请求
                //.failureForwardUrl("/toError")
                //失败后处理器，不能和 failureForwardUrl共存
                .failureHandler(new MyAuthentiactionFailurHandler("/error.html"))
                //登录是自定义的用户名参数名
                .usernameParameter("uname")
                //自定义的登录密码参数名
                .passwordParameter("upass");

        //授权
        http.authorizeRequests()
                //放行error页面不拦截
                .antMatchers("/error.html").permitAll()
                //不需要拦截的登录请求和登录页面
                //.antMatchers("/login.html").permitAll()
                //.mvcMatchers("/demo").servletPath("/xxxx").permitAll()
                //.antMatchers("/demo").hasAnyAuthority("admin","nomal")
                //.antMatchers("/demo").hasRole("admin")
                //.antMatchers("/demo").hasAnyRole("admin","abc")
                .antMatchers("/login.html").access("permitAll()")
                //.antMatchers("/main1.html").hasAuthority("abc")
                //ip地址判断
                //.antMatchers("/mian").hasIpAddress("127.0.0.0")
                //拦截所有请求 只有被认证才能访问
                .anyRequest().authenticated();
                //自定义的拦截 入参
                //.anyRequest().access("@myserviceImpl.hasPremission(request,authentication)");

        //异常处理
        http.exceptionHandling()
                .accessDeniedHandler(myAccessDeniedHandler);

        //关闭csrf防护 >只有关闭了,来自表单的请求
        http.csrf().disable();
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
